package org.finesys.samples.file.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class BioServer {


    public static void main(String[] args) {

        try {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress(8080));

            while (true) {
                //
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                System.out.println("客户端连接成功");
                //为每一个客户端都创建一个独立的线程进行数据处理，避免因为处理逻辑复杂，导致的线程阻塞，后续客户端无法连接。
                // 当客户端断开时会抛异常，服务端需要对每一个独立的客户端线程都进行捕获异常的处理，否则会因为客户端的断开，服务端也宕掉
                new Thread(() -> {

                    long threadId = Thread.currentThread().getId();
                    try {
                        //给客户端发送消息
                        PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
                        printWriter.println("当前线程[" + threadId + "]欢迎来到服务端");
                        //接收来自客户端的消息
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        while (true) {
                            String message = bufferedReader.readLine();
                            if (message == null) {
                                break;
                            }
                            System.out.println("当前线程[" + threadId + "]接收到消息：" + message);
                        }

                    } catch (IOException e) {
                        System.out.println("当前线程[" + threadId + "]关闭客户端：" + e.getMessage());
                    } finally {
                        if (socket != null) {
                            //关闭流
                            try {
                                socket.getInputStream().close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                socket.getOutputStream().close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                socket.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

    }
}
